let chatName;
$(document).ready(function() {
    /**
     * 获取上一个页面传入的参数
     * */
    function getQueryParam(name) {
        let regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
            results = regex.exec(window.location.href);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }
    let roomName = getQueryParam('roomName');
    chatName = roomName;
    let formData = new FormData();
    console.info(roomName);
    formData.append("roomName",roomName);
    CountAnalysisTable(formData);
    DialoguesAnalysis(formData);
    //var msgCount = echarts.init(document.getElementById('msgCount'));

    //fetchCountChartData(formData); // 调用chart.js中导出的函数
});
function CountAnalysisTable(formData){
    console.log("调用了统计信息",formData.get("roomName"))
    $.ajax({
        url:'DisAnalysis',
        type:'post',
        data:formData,
        async: false,
        contentType: false,
        processData: false,
        success:function (res){
            if(res.code === 200){
                console.log(res.data);
                let DisAnalysis = [
                    { name: '讨论主题', content: res.data.item},
                    { name: '讨论内容', content: res.data.content},
                    { name: '讨论重点', content: res.data.contentKey},
                    { name: '小组成员总数', content: res.data.studentCount},
                    { name: '小组讨论时长', content: res.data.duration},
                    { name: '小组发言总数', content: res.data.msgCount},
                    { name: '小组提问总数', content: res.data.questionCount}
                ];
                // 清空表格内容（如果需要）
                $('#count-result-table tbody').empty();
                // 遍历后端数据
                $.each(DisAnalysis, function(index, item) {
                    // 创建新的行元素
                    let $newRow = $('<tr></tr>');
                    // 创建新的单元格元素并设置内容
                    let $nameCell = $('<td></td>').text(item.name);
                    let $ageCell = $('<td></td>').text(item.content);
                    // 将单元格添加到行中
                    $newRow.append($nameCell, $ageCell);
                    // 将行添加到表格中
                    $('#count-result-table tbody').append($newRow);
                });
            }else{
                console.log("数据统计分析失败！");
            }
        },
        error:function (res){
            cocoMessage.info("res.data");
        }
    })
}

function CountQuestionsTable(formData){
    console.log("调用了问题统计信息",formData.get("roomName"))
    $.ajax({
        url:'loadingAnswer',
        type:'post',
        data:formData,
        async: false,
        contentType: false,
        processData: false,
        success:function (res){
            if(res.code === 200){
                console.log(res.data);
                // 清空表格内容（如果需要）
                $('#count-questions-result-table tbody').empty();
                // 遍历后端数据
                for (let i = 0; i < res.data.length;) {
                    let item = res.data[i];
                    let $newRow = $('<tr></tr>');
                    // 创建新的单元格元素并设置内容
                    let $numberCell = $('<td></td>').text(i);
                    let $studentCell = $('<td></td>').text(item.username);
                    let $questionCell =$('<td></td>').text(item.content);
                    let $answerCell = $('<td></td>').text(res.data[i+1].content);
                    i+=2;
                    $newRow.append($numberCell, $studentCell,$questionCell,$answerCell);
                    // 将行添加到表格中
                    $('#count-questions-result-table tbody').append($newRow);
                }
            }else{
                console.log("问题统计失败！");
            }
        },
        error:function (res){
            cocoMessage.info("res.data");
        }
    })
}
// 从后端获取数据并生成图表
function fetchChartData() {
    $.get('/chartData', function(data) {
        // 转换数据为ECharts所需的格式
        var chartData = data.map(function(item) {
            return {
                name: item.name,
                value: item.value
            };
        });

        // 定义图表的配置项和数据
        var option = {
            title: {
                text: '示例图表'
            },
            tooltip: {},
            xAxis: {
                data: chartData.map(function(item) {
                    return item.name;
                })
            },
            yAxis: {},
            series: [{
                name: '值',
                type: 'bar',
                data: chartData.map(function(item) {
                    return item.value;
                })
            }]
        };
        // 使用刚指定的配置项和数据显示图表。
        msgCount.setOption(option);
    });
}

function fetchCountChartData(formData) {
    $.ajax({
        url: '/chatData/',
        type: 'post',
        data: formData,
        async: false,
        contentType: false,
        processData: false,
        success:function (res) {
            if (res.code === 200) {
                console.info(res.data);
                let allMsgCount = res.data.AllMsgCount;
                let chatRoom = res.data.chatRoom;
                let leader = res.data.leader;
                let chartData = res.data.disAnalysis;
                let numbers = res.data.numbers
                //console.info(chartData);
                let names=chartData.name;
                let counts=chartData.count;
                let questions=chartData.questions;
                console.log("allMsgCount"+allMsgCount);
                console.log("chatRoom"+chatRoom.toString());
                console.log("leader"+leader.toString());
                console.log("chartData"+chartData.toString());
                console.log("numbers"+numbers);
                console.log("names"+names);
                console.log("counts"+counts);
                console.log("questions"+questions);

                // 定义图表的配置项和数据
                var option = {
                    title: {
                        text: '示例图表'
                    },
                    tooltip: {},
                    xAxis: {
                        data: names,
                    },
                    yAxis: {},
                    series: [{
                        name: '值',
                        type: 'bar',
                        data: counts,
                    }]
                };
                // 使用刚指定的配置项和数据显示图表。
                msgCount.setOption(option);

            }else {
                console.info("拉取分析数据失败");
                // 重定向到登录页
                //window.location.href = '/loginPage';
            }
        },
        error: function (res) {
            console.log(res.data);
            console.info("拉取分析数据错误");
            // 重定向到登录页
            //window.location.href = '/loginPage';
        }
        /*error: function(jqXHR, textStatus, errorThrown) {
            // 处理错误
            console.error('AJAX 请求失败: ' + textStatus);
        }*/
    })
}
// 导出函数，以便在HTML中调用
window.fetchCountChartData = fetchCountChartData;

$('.question-count').click(function (){
    let roomName = chatName;
    let formData = new FormData();
    console.info(roomName);
    formData.append("roomName",roomName);
    CountQuestionsTable(formData);
    showQuestionCountModel();
});


/**
 * 点击页面其他面板，新增模板消失
 * */
$('.overlay').click(function () {
    hiddenQuestionCountModel();
});

function hiddenQuestionCountModel(){
    $('.overlay').css('z-index', '');
    $('.question-count-model').css('visibility', 'hidden');
    $('.show-img').css('visibility', 'hidden');
}

function showQuestionCountModel() {
    $('.overlay').css('z-index', '1');
    $('.question-count-model').css('visibility', 'visible');
}

/**
 * 调用讨论深度分析
 * */
function DialoguesAnalysis(formData){
    console.log("调用了讨论深度分析");
    console.log(formData);
    $.ajax({
        url: '/DialoguesAnalysis/',
        type: 'post',
        data: formData,
        contentType: false,
        processData: false,
        success: function (res) {
            if (res.code === 200) {
                console.info("讨论内容分析结果："+res.data);

                $('#dialogue-analysis-result-table tbody').empty();
                // 遍历后端数据
                for (let i = 0; i < res.data.length;) {
                    let item = res.data[i];
                    let $newRow = $('<tr></tr>');
                    // 创建新的单元格元素并设置内容
                    let $numberCell = $('<td></td>').text(i);
                    let $studentCell = $('<td></td>').text(item.username);
                    let $questionCell =$('<td></td>').text(item.content);
                    let $answerCell = $('<td></td>').text(res.data[i+1].content);
                    i+=2;
                    $newRow.append($numberCell, $studentCell,$questionCell,$answerCell);
                    // 将行添加到表格中
                    $('#count-questions-result-table tbody').append($newRow);
                }
            } else {
                alert("讨论内容分析失败");
            }
        }
    });
}